package com.yoomiito.app.widget.songduoduo

import android.content.Context
import com.google.android.material.tabs.TabLayout
import androidx.viewpager.widget.PagerAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import cn.droidlover.xdroidmvp.net.ApiException
import cn.droidlover.xdroidmvp.net.ApiSubscriber
import cn.droidlover.xdroidmvp.net.BaseModel
import cn.droidlover.xdroidmvp.net.XApi
import com.yoomiito.app.MainActivity
import com.yoomiito.app.R
import com.yoomiito.app.model.BaseList
import com.yoomiito.app.model.sdd.SddFreeGoodsOrderInfo
import com.yoomiito.app.net.YmApi
import com.yoomiito.app.showToast
import com.yoomiito.app.ui.list.ReceiveListOfGiftActivity
import com.yoomiito.app.ui.list.ReceiverListAdapter
import com.yoomiito.app.ui.songduoduo.SendMoreActivity
import com.yoomiito.app.utils.*
import com.yoomiito.app.widget.SpacingDecoration
import com.yoomiito.app.widget.dialog.SendGoodsDialog
import com.yoomiito.app.widget.state.ContentType
import com.yoomiito.app.widget.state.EmptyType_1
import com.yoomiito.app.widget.state.StatusManager
import kotlinx.android.synthetic.main.layout_giver_list.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 送多多---赠品领取名单
 */
class GiverListView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0)
    : LinearLayout(context, attrs, defStyleAttr, defStyleRes) {
    private val l = DensityUtil.dp2px(0f)
    private val t = DensityUtil.dp2px(12f)
    private val b = DensityUtil.dp2px(12f)
    //    val data = arrayListOf("", "", "", "", "", "", "", "", "", "")
    private val tabs = arrayOf("待确认", "其他")
    private val adapter1 = ReceiverListAdapter(null)
    private val adapter2 = ReceiverListAdapter(null)
    companion object{
        const val type_0 = 0 //待确认
        const val type_1 = 1 //其他
    }
    private var mCurrentType= type_0
    private val orderStatus = arrayOf("已超时","已拒绝","已领取","已收货")
    private val statusView1 = StatusManager.Builder(context)
            .addType(ContentType(R.layout.item_rcy))
            .addType(EmptyType_1().setEmptyContent("暂无待确认名单").setmHeight(DensityUtil.dp2px(123f)))//123
            .build()

    private val statusView2 = StatusManager.Builder(context)
            .addType(ContentType(R.layout.item_rcy))
            .addType(EmptyType_1().setEmptyContent("暂无数据").setmHeight(DensityUtil.dp2px(123f)))
            .build()

    private val rcy1 = statusView1.view().findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.layoutRcy).let {
        it.setPadding(l, t, l, b)
        it.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context, androidx.recyclerview.widget.LinearLayoutManager.HORIZONTAL, false)
        it.addItemDecoration(SpacingDecoration(DensityUtil.dp2px(12f), DensityUtil.dp2px(0f), true))
        adapter1.setOnItemChildClickListener { adapter, view, position ->
            val item = adapter1.data[position]
            val dialog = SendGoodsDialog(context,item)
            dialog.onResultListener={b->
                dialog.dismiss()
                reviewStatus(item,if (b)0 else 1)
            }
            dialog.show()
        }
        it.adapter = adapter1
    }

    private val rcy2 = statusView2.view().findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.layoutRcy).let {
        it.setPadding(l, t, l, b)
        it.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context, androidx.recyclerview.widget.LinearLayoutManager.HORIZONTAL, false)
        it.addItemDecoration(SpacingDecoration(DensityUtil.dp2px(12f), DensityUtil.dp2px(0f), true))
        it.adapter = adapter2
    }

    private val views = arrayOf<View>(statusView1.view(), statusView2.view())

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.layout_giver_list, null, false)
        val lp = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
        addView(view, lp)

        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(p0: TabLayout.Tab?) {

            }

            override fun onTabUnselected(p0: TabLayout.Tab?) {
            }

            override fun onTabSelected(p0: TabLayout.Tab?) {
                mCurrentType = if (p0?.position==0) type_0 else type_1
            }

        })
        viewPager.adapter = VPAdapter()
        tabLayout.setupWithViewPager(viewPager)
        more.setOnClickListener {
            ReceiveListOfGiftActivity.start(context,mCurrentType)
        }
//        updateData()
    }

    fun updateData(){
        sddFreeGoodsOrderLIst(type_0)
        sddFreeGoodsOrderLIst(type_1)
    }

    /**
     * 送多多--领取审核
     */
    private fun reviewStatus(data:SddFreeGoodsOrderInfo,status:Int){
        val act = context as SendMoreActivity
        YmApi.getYmService()
                .sddConfirmGift(data.id.toString(),status)
                .compose(act.bindToLifecycle())
                .compose(XApi.getApiTransformerNoData<BaseModel<*>>())
                .compose(XApi.getScheduler())
                .subscribe(object : ApiSubscriber<BaseModel<*>>(){
                    override fun onSuccess(t: BaseModel<*>?) {
                        val msg = EventMessage()
                        msg.eventType = Type.EventMsgType.SDD_UPDATE_DATA
                        EventBus.getDefault().post(msg)
                        updateData()
                        act.dismissLoading()
                        "${data.nickname}成功领取商品".showToast()
                    }

                    override fun onFail(error: ApiException?) {
                        error?.msg?.showToast()
                        updateData()
                        act.dismissLoading()
                    }
                })
    }

    /**
     * 送多多--赠品订单列表
     */
    private fun sddFreeGoodsOrderLIst(type:Int){
        YmApi.getYmService()
                .sddFreeGoodsOrderList(type,1, Const.PageSize.Size_10)
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(object : ApiSubscriber<BaseList<SddFreeGoodsOrderInfo>>(){
                    override fun onSuccess(t: BaseList<SddFreeGoodsOrderInfo>?) {
                        when(type){
                            type_0->{
                                if (t?.data!=null&&t?.data.isNotEmpty()){
                                    adapter1.setNewData(t?.data)
                                    statusView1.showContent()
                                }else{
                                    adapter1.setNewData(null)
                                    statusView1.showEmpty(EmptyType_1::class.java)
                                }
                            }
                            type_1->{
                                if (t?.data!=null&&t?.data.isNotEmpty()){
                                    adapter2.setNewData(t?.data)
                                    statusView2.showContent()
                                }else{
                                    adapter2.setNewData(null)
                                    statusView2.showEmpty(EmptyType_1::class.java)
                                }
                            }
                        }
                    }

                    override fun onFail(error: ApiException?) {

                    }

                })
    }

    inner class VPAdapter : androidx.viewpager.widget.PagerAdapter() {

        override fun isViewFromObject(p0: View, p1: Any): Boolean = p0 == p1

        override fun getCount(): Int = views.size

        override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            container.removeView(`object` as View)
        }

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            container.addView(views[position])
            return views[position]
        }

        override fun getPageTitle(position: Int): CharSequence? {
            return tabs[position]
        }
    }

//    inner class RcyAdapter : BaseQuickAdapter<SddFreeGoodsOrderInfo, BaseViewHolder>(R.layout.item_receiver, null) {
//        override fun convert(helper: BaseViewHolder?, item: SddFreeGoodsOrderInfo?) {
//
//        }
//
//    }
}